/**
 * 
 */
package it.battlehorse.scripting.actions;

import it.battlehorse.rcp.sl.annot.Injected;
import it.battlehorse.rcp.sl.annot.Serviceable;
import it.battlehorse.scripting.ScriptSupport;
import it.battlehorse.scripting.ScriptingActivator;
import it.battlehorse.scripting.registry.IScript;

import javax.script.ScriptException;

import org.apache.commons.logging.Log;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;


/**
 * This action works as a proxy for <code>scriptedActions</code>. It plugs into the eclipse workbench (by 
 * implementing <code>IWorkbenchWindowActionDelegate</code> ) and delegates execution requests to the associated
 * script.
 * 
 * @author battlehorse
 *
 */
@Serviceable
public class ScriptProxyAction implements IWorkbenchWindowActionDelegate {
	
	private Log log ; 
	
	@Injected
	public void setLog(Log log) {
		this.log = log;
	} 
	
	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
	 */
	public void dispose() {
		// nothing to do
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
	 */
	public void init(IWorkbenchWindow window) {
		// nothing to do
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		IScript script = ScriptingActivator.getDefault().getScriptingRegistry().getScriptFromId(action.getId());
		
		try {
			new ScriptSupport().runScript(script);
		}
		catch(ScriptException se) {
			log.error("An error occurred while running script " + script.getId() + ": " + se.getMessage(),se);
		}

		
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		// nothing to do

	}

}
